package com.agileai.portal.handler;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.agileai.domain.DataParam;
import com.agileai.hotweb.common.BeanFactory;
import com.agileai.hotweb.controller.core.BaseHandler;
import com.agileai.hotweb.domain.core.Profile;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.RedirectRenderer;
import com.agileai.hotweb.renders.ViewRenderer;

public class LoginHandler extends BaseHandler {
	public ViewRenderer prepareDisplay(DataParam param) {
		return new LocalRenderer(getPage());
	}	
	public ViewRenderer doLoginAction(DataParam param){
		ViewRenderer result = null;
		String responseText = "";
		String userId = param.get("userId");
		String userPwd = param.get("userPwd");

		if (userId.equals(userPwd) && "admin".equals(userId)){
			String fromIpAddress = request.getLocalAddr();
			Profile profile = new Profile(userId,fromIpAddress,userId);
			HttpSession session = request.getSession();
			session.setAttribute(Profile.PROFILE_KEY, profile);
			String defaultInNavId = BeanFactory.instance().getAppConfig().getConfig("GlobalConfig","DefaultInNavId");
			responseText = "sucess;forward?"+defaultInNavId;
			result = new AjaxRenderer(responseText);
		}
		else{
			result = new AjaxRenderer("fail;userId or userPwd is error !");
		}
		return result;
	}
	
	@SuppressWarnings("unchecked")
	public ViewRenderer doLogoutAction(DataParam param) throws ServletException, IOException{
		ViewRenderer result = null;
		HttpSession session = this.request.getSession();
		String sessionId = session.getId();
		ServletContext context = this.request.getServletContext();
		HashMap<String,HttpSession> sessionMap = (HashMap<String,HttpSession>)context.getAttribute(Profile.CrossSessionMapKey);
		if(sessionMap != null) {
			sessionMap.remove(sessionId);
		}
		session.removeAttribute(Profile.PROFILE_KEY);
		session.invalidate();
		
		this.clearCookie(request, response,"/");
		
		String casServerLogoutUrl = this.dispatchServlet.getServletContext().getInitParameter("casServerLogoutUrl");
		String serverName = this.dispatchServlet.getServletContext().getInitParameter("serverName");
		String redirectUrl = casServerLogoutUrl + "?service="+ serverName+this.dispatchServlet.getServletContext().getContextPath();
//		String defaultOutNavId = BeanFactory.instance().getAppConfig().getConfig("GlobalConfig","DefaultOutNavId");
//		result = new RedirectRenderer("forward?"+defaultOutNavId);
		result = new RedirectRenderer(redirectUrl);
	    return result;
	}
	
	private void clearCookie(HttpServletRequest request, HttpServletResponse response, String path) {
		Cookie[] cookies = request.getCookies();
		try {
			for (int i = 0; i < cookies.length; i++) {
//				System.out.println(cookies[i].getName() + ":" + cookies[i].getValue());
				Cookie cookie = new Cookie(cookies[i].getName(), null);
				cookie.setMaxAge(0);
				cookie.setPath(path);
				response.addCookie(cookie);
			}
		} catch (Exception ex) {
			System.out.println("清空Cookies发生异常！");
		}
	}
}
